package myoa

import myoa.tool.AbstractServletTool
import myoa.tool.SessionTool
import org.springframework.web.multipart.MultipartFile
import org.springframework.web.multipart.MultipartHttpServletRequest

class FileStoreService extends AbstractServletTool {
    FileStore upload() {
        upload('file')   //default for file
    }

    /**
     *  upload file to server dir and save fileStore object in db
     * @param name in gsp form field <input type="file" name="file"/>
     */
    FileStore upload(String name) {         //todo 事务化
        FileStore fs = new FileStore(name: 'temp')
        fs.traceCreate()
        fs.save()  // save for get id

        MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request
        MultipartFile multiFile = multiRequest.getFile(name)
        String uniqueName = "${fs.id}_${SessionTool.loginUser.name}_${multiFile.originalFilename}"
        fs.name = uniqueName

        multiFile.transferTo(fs.file)
        fs.save()
        return fs
    }
}
